<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between" align="center">
        <NSpace align="center">
          类型：
          <NSelect style="width: 240rem;" placeholder="请选择类型" v-model:value="paginationReactive.linkType" :options="[
            { label: '藏品', value: '1' },
            { label: 'OA', value: '2' }
          ]" clearable ></NSelect>
          状态：
          <NSelect style="width: 240rem;" placeholder="请选择状态" v-model:value="paginationReactive.linkStatus" :options="[
            { label: '启用', value: '1' },
            { label: '禁用', value: '2' }
          ]" clearable ></NSelect>
          <NButton type="primary" style="width: 78px" @click="queryTableData(true)" ghost>
            查询
          </NButton>
        </NSpace>
        <NSpace align="center">
          <NButton type="primary" style="width: 78px" @click="handleAdd">
            新增
          </NButton>
        </NSpace>
      </NSpace>

    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againDelete" title="删除提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import { NButton, NDataTable, NPagination, NSpace, useMessage, NP, NModal, NSelect } from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated } from 'vue'
import type { DataTableColumns } from 'naive-ui'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import type { HttpResponsePagination } from '@/utils/http'
import type { customlistModel } from '@/api/office'
import { useViewerStore } from '../Common/store'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import upIcon from '@/assets/images/up_logo.png?url'
import lowIcon from '@/assets/images/low_logo.png?url'
import topIcon from '@/assets/images/top_logo.png?url'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

//表格
const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    fixed: 'left',
    title: '排序',
    key: 'orderIndex',
    render: (_, i) => {
      return ++i + (paginationReactive.page - 1) * paginationReactive.pageSize
    },
    width: '20rem',
    align: useStore.isCenter
  },
  {
    title: '名称',
    key: 'name',
    width: '30rem',
    align: useStore.isCenter
  },
  {
    title: '类型',
    key: 'linkType',
    width: '30rem',
    align: useStore.isCenter,
    render: ({ linkType }) => {
      return linkType == 2 ? 'OA' : '藏品'
    }
  },
  {
    title: '状态',
    key: 'linkStatus',
    width: '30rem',
    align: useStore.isCenter,
    render: ({ linkStatus }) => {
      return linkStatus == 1 ? '启用' : '禁用'
    }
  },
  {
    title: '图标',
    key: 'url',
    width: '40rem',
    align: useStore.isCenter,
    render(e) {
      return h('div', null, [
        h('img', {
          style: 'height:50rem;width:50rem;border-radius:50%;border:1px solid #ccc',
          src: e?.filePath ? e?.filePath : 'http://211.90.243.252:8096/hzbbgUpload/upload/basic/20240202/1706838216674.png'
        })
      ])
    }
  },
  {
    title: 'URL',
    key: 'url',
    width: '100rem',
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: useStore.isCenter,
    width: '50rem',
    fixed: 'right',
    render: (e: any, index: any) => [
      h('div', {
        style: {
          display: 'flex',
          alignItems: 'center'
        }
      }, {
        default: () => [
          h(
            NButton,
            { type: 'primary', quaternary: true, onClick: () => handleEdit(e) },
            {
              default: () => '编辑'
            }
          ),
          h(
            NButton,
            {
              type: 'warning',
              quaternary: true,
              color: useStore.color['delete'],
              onClick: () => handleDelete([e?.id])
            },
            {
              default: () => '删除'
            }
          ),
          h(
            'img',
            {
              style: {
                margin: '3px 15rem',
                width: '16rem',
                height: '16rem',
                cursor: 'pointer',
                // display: index + (paginationReactive.page - 1) * paginationReactive.pageSize ? 'inline' : 'none'
                display: e.sort ? 'inline' : 'none'
              },
              src: upIcon,
              onClick: () => handleUp(e.id)
            },
            {
              default: () => upIcon
            }
          ),
          h(
            'img',
            {
              style: {
                margin: '3px 15rem',
                width: '16rem',
                height: '16rem',
                cursor: 'pointer',
                // display: index + (paginationReactive.page - 1) * paginationReactive.pageSize + 1 != paginationReactive.itemCount ? 'inline' : 'none'
                display: e.sort != paginationReactive.itemCount ? 'inline' : 'none'
              },
              src: lowIcon,
              onClick: () => handleLow(e.id)
            },
            {
              default: () => lowIcon
            }
          ),
          h(
            'img',
            {
              style: {
                margin: '3px 15rem',
                width: '16rem',
                height: '16rem',
                cursor: 'pointer',
                // display: index - 1 + (paginationReactive.page - 1) * paginationReactive.pageSize + 1 ? 'inline' : 'none'
                display: e.sort ? 'inline' : 'none'
              },
              src: topIcon,
              onClick: () => handleTop(e.id)
            },
            {
              default: () => topIcon
            }
          )
        ]
      })
    ]
  }
]
// 页码
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  linkType: null,
  linkStatus: null,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
//新增
const handleAdd = () => router.push({ path: '/OA/Office/H5CustomAdd' })
// 编辑
const handleEdit = (val: any) => router.push({ path: '/OA/Office/H5CustomUpdate', query: { id: val.id } })
//删除弹窗
const modalVisible = ref(false)
const modalId = ref()
const againDelete = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'office',
    api: 'mobileLinkDelete',
    override: {
      data: modalId.value
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success('删除成功')
  modalVisible.value = false
  tableLoading.value = false
  tableData.value = []
  setTimeout(() => {
    queryTableData()
  }, 0);
}
// 删除
const handleDelete = (val: any) => {
  modalId.value = val
  modalVisible.value = true
}
//上移
const handleUp = async (val: any) => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'office',
    api: 'mobileLinkMoveUp',
    override: {
      params: {
        id: val
      }
    }
  })
  if (error) return message.error(error.message), tableLoading.value = false
  if (res.code !== 0) return message.error(res.msg), tableLoading.value = false
  message.success(res.data)
  queryTableData()
}
//下移
const handleLow = async (val: any) => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'office',
    api: 'mobileLinkMoveDown',
    override: {
      params: {
        id: val
      }
    }
  })
  if (error) return message.error(error.message), tableLoading.value = false
  if (res.code !== 0) return message.error(res.msg), tableLoading.value = false
  message.success(res.data)
  queryTableData()
}
//置顶
const handleTop = async (val: any) => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'office',
    api: 'mobileLinkMoveToTop',
    override: {
      params: {
        id: val
      }
    }
  })
  if (error) return message.error(error.message), tableLoading.value = false
  if (res.code !== 0) return message.error(res.msg), tableLoading.value = false
  message.success(res.data)
  queryTableData(true)
}
//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<customlistModel[]>>({
    module: 'office',
    api: 'mobileLinkList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        linkType: paginationReactive.linkType,
        linkStatus: paginationReactive.linkStatus
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = res.data.list
  paginationReactive.itemCount = res.data.totalCount
}

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route.path,
  () => {
    if (route.path == '/OA/Office/H5CustomSetting') {
      queryTableData(true)
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
</style>
